package com.portal.gateway.handler;

import com.portal.common.core.exception.CaptchaException;
import com.portal.common.core.web.domain.AjaxResult;
import com.portal.gateway.service.ValidateCodeService;
import com.portal.gateway.service.WeatherService;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 验证码获取
 *
 * @author portal
 */
@Component
public class WeatherRealTimeHandler implements HandlerFunction<ServerResponse>
{
    @Resource
    private WeatherService weatherService;

    @Override
    public Mono<ServerResponse> handle(ServerRequest serverRequest)
    {
        AjaxResult ajax;
        try
        {
            String clientIp = getClientIpAddress(serverRequest);
            ajax = weatherService.getWeather(clientIp);
        }
        catch (Exception e)
        {
            return Mono.error(e);
        }
        return ServerResponse.status(HttpStatus.OK).body(BodyInserters.fromValue(ajax));
    }
    private String getClientIpAddress(ServerRequest serverRequest) {
        String ip = serverRequest.headers().firstHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = serverRequest.headers().firstHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = serverRequest.headers().firstHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = serverRequest.headers().firstHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = serverRequest.headers().firstHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = serverRequest.remoteAddress().map(address -> address.getAddress().getHostAddress()).orElse(null);
        }
        return ip;
    }
}
